package com.web.wx.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.DocumentException;
import com.alibaba.fastjson.JSONObject;
import com.common.tool.HttpRequest;
import com.common.tool.WeiXinUtil;
import com.dao.MemberAddress;
import com.dao.MemberBuy;
import com.dao.MemberShopReq;
import com.dao.SettingMemberType;
import com.dao.WeixinMemberInfoUtil;
import com.dao.WeixinSubscribe;
import com.dao.WeixinUserinfo;
import com.entity.CommonConstant;
import com.entity.weixin.PayCommonUtil;
import com.entity.weixin.TextMessage;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;

public class WeiXinController extends Controller {
    String token = "weixin";

   
    public void getIptest() {
	try {
	    String hostAddress = InetAddress.getLocalHost().getHostAddress().toString();
	    System.out.println("hostAddress:" + hostAddress);
	    String hostName = InetAddress.getLocalHost().getHostName();
	    System.out.println("hostName:" + hostName);
	    if (hostName.length() > 0) {
		InetAddress[] addrs = InetAddress.getAllByName(hostName);
		if (addrs.length > 0) {
		    for (int i = 0; i < addrs.length; i++) {
			InetAddress address = addrs[i];
			System.out.println("**********************");
			System.out.println(address.getHostAddress());
			if (address instanceof Inet6Address) {
			    System.out.println("true6");
			} else if (address instanceof Inet4Address) {
			    System.out.println("true4");
			} else {
			    System.out.println("unknown");
			}
			System.out.println("**********************");

		    }
		}
	    }
	} catch (UnknownHostException e) {
	    e.printStackTrace();
	}
    }

    public void index() throws IOException, DocumentException {
	System.out.println("getRemoteAddr::::"+this.getRequest().getRemoteAddr());
	System.out.println("getLocalAddr::::"+this.getRequest().getLocalAddr());
	String openid = null;
	if (this.getSessionAttr("openid") != null) {
	    openid = this.getSessionAttr("openid").toString();
	}
	if (openid == null && this.getAttr("weixinOpenid") != null) {
	    openid = this.getAttr("weixinOpenid").toString();
	}
	System.out.println("weixin::::" + this.getSessionAttr("openid"));
	if (openid != null) {
	    setAttr("weixinOpenid", openid);
	} else {
	    String CodeUrl = "";
	    if (this.getPara("code") != null) {
		System.out.println(this.getPara("code").toString());
		System.out.println(this.getPara("state").toString());
		String openId = oauth2Url(this.getPara("code"));
	    }
	    // {"access_token":"FsU-lPd7ls8QKV8X34hXGcLu15T3Kvf2MWOitt_NlprvuTyDrrQbODrPG_Qx0TxLUBBGejBYvj7IeA4JPzUH8qFR6jmk7Mv8vOnLnFDRKSw","expires_in":7200,"refresh_token":"jwQRLFt8HuEZ3Q8YE0xiVm3Vx_MJ3aLHD63OWdqbLuCd9IDU1I6TDndQMkh-gp922n2tAOgNCWFaZets8pgIAdlKEmU_W8_S3M_mqvY2Oqo","openid":"otFedvw6QnZPsLI2RqVg25nmW5sw","scope":"snsapi_base"}
	}
	this.renderJsp("/weixin/index.jsp");
	// render("/weixin/index.html");
    }

    /**
     * 微信认证 @Title: weixinindex @Description: TODO(这里用一句话描述这个方法的作用) @param
     * 设定文件 @return void 返回类型 @throws
     */
    public void weixinindex() {
	String openId = null;
	System.out.println("this.getPara code :::" + this.getPara("code"));
	if (this.getSessionAttr("openId") != null) {
	    openId = this.getSessionAttr("openId");
	} else {
	    if (this.getPara("code") != null) {
		System.out.println(this.getPara("code").toString());
		System.out.println(this.getPara("state").toString());
		openId = oauth2Url(this.getPara("code"));
		this.setSessionAttr("openId", openId);
	    }
	}
	System.out.println("首页openid:" + openId);
        System.out.println("getRemoteAddr::::"+this.getRequest().getRemoteAddr());
	System.out.println("getLocalAddr::::"+this.getRequest().getLocalAddr());
	this.renderJsp("/weixin/weixin_index.jsp");
    }

    public void category() {
	// render("/weixin/category.html");
	String openid = null;
	if (this.getSessionAttr("openid") != null) {
	    openid = this.getSessionAttr("openid").toString();
	}
	if (openid == null && this.getAttr("weixinOpenid") != null) {
	    openid = this.getAttr("weixinOpenid").toString();
	}
	this.setAttr("weixinOpenid", openid);
	this.renderJsp("/weixin/category.jsp");
    }

    /**
     * 
     * @Title: members @Description: 个人中心，微信验证跳转得到openId @param 设定文件 @return
     *         void 返回类型 @throws
     */
    public void members() {
	String openId = null;
	if (this.getSessionAttr("openId") != null) {
	    openId = this.getSessionAttr("openId");
	} else {
	    if (this.getPara("code") != null) {
		openId = oauth2Url(this.getPara("code"));
		this.setSessionAttr("openId", openId);
	    }
	}
	System.out.println("个人中心openid:" + openId);
	if (openId == null) {
	    openId = "orUWqv9PXkMkWv_ge6P0LD6DxM8Q";
	}
	String memeberType = WeixinMemberInfoUtil.getWeixinSubscribe(openId).getMembertypecode();
	SettingMemberType sysMemeberType = WeixinMemberInfoUtil.getMemberType(memeberType);
	this.setAttr("sysMemeberType", sysMemeberType);
	this.renderJsp("/weixin/members.jsp");
    }

    public void memberfriends() {
	String openId = "";
	if (this.getSessionAttr("openId") != null) {
	    openId = this.getSessionAttr("openId").toString();
	}
	System.out.println("openId::::" + openId);
	if (openId != null) {
	    StringBuilder sql = new StringBuilder("select * from weixin_subscribe where recommend_username= '")
		    .append(openId).append("'");

	    System.out.println("first sql:" + sql);
	    List<WeixinSubscribe> firstSubscribe = WeixinSubscribe.dao.find(sql.toString());
	    this.setAttr("firstSubscribe", firstSubscribe);

	    sql = new StringBuilder("select * from weixin_subscribe where recommend_username in ")
		    .append(" (select fromusername from weixin_subscribe where recommend_username='").append(openId)
		    .append("')");
	    System.out.println("second sql:" + sql);
	    List<WeixinSubscribe> secondSubscribe = WeixinSubscribe.dao.find(sql.toString());
	    this.setAttr("secondSubscribe", secondSubscribe);

	    sql = new StringBuilder("select * from weixin_subscribe where recommend_username in ")
		    .append("(select fromusername from weixin_subscribe where recommend_username in ")
		    .append("(select fromusername from weixin_subscribe where recommend_username='").append(openId)
		    .append("'))");
	    System.out.println("third sql:" + sql);
	    List<WeixinSubscribe> thirdSubscribe = WeixinSubscribe.dao.find(sql.toString());
	    this.setAttr("thirdSubscribe", thirdSubscribe);
	}
	this.renderJsp("/weixin/member-firends.jsp");

    }

    public void memberproducts() {
	
	String openId = "";
	if (this.getSessionAttr("openId") != null) {
	    openId = this.getSessionAttr("openId").toString();
	}
	
	//所有的订单，不包括删除的，buystate=-1 
	String whereSql ="  openid='"+openId+"'";
	String orderSql=" order by createtime desc";
	String selectSql="select * from member_buy ";
	StringBuilder sql = new StringBuilder(selectSql);
	if(!"".equals(openId)){
	    sql.append(" where ").append(whereSql);
	}
	sql.append(orderSql);
	
	List<MemberBuy> allOrderLst= MemberBuy.dao.find(sql.toString());
	this.setAttr("allOrderLst", allOrderLst);
	
	//待付款的订单，buystate = 1 and paystate!=1
	sql = new StringBuilder(selectSql).append(" where buystate=1 and paystate!=1 ");
	if(!"".equals(openId)){
	    sql.append(" and ").append(whereSql);
	}
	sql.append(orderSql);
	List<MemberBuy> toPayOrderLst= MemberBuy.dao.find(sql.toString());
	this.setAttr("toPayOrderLst", toPayOrderLst);
	
	//待发货的订单 paystate=1 and poststate =0
	sql = new StringBuilder(selectSql).append(" where paystate=1 and poststate =0 ");
	if(!"".equals(openId)){
	    sql.append(" and ").append(whereSql);
	}
	sql.append(orderSql);
	List<MemberBuy> toPostOrderLst= MemberBuy.dao.find(sql.toString());
	this.setAttr("toPostOrderLst", toPostOrderLst);
	
	//退货的buystate=-2
//	sql = new StringBuilder(selectSql).append(" where buystate=-2");
//	if(!"".equals(openId)){
//	    sql.append(" and ").append(whereSql);
//	}
//	sql.append(orderSql);
//	List<MemberBuy> toBackOrderLst= MemberBuy.dao.find(sql.toString());
//	this.setAttr("toBackOrderLst", toBackOrderLst);
	
	
	
	sql = new StringBuilder(selectSql).append(" where poststate =1  and  confirmstate =0 ");
	if(!"".equals(openId)){
	    sql.append(" and ").append(whereSql);
	}
	sql.append(orderSql);
	List<MemberBuy> toConfirmOrderLst= MemberBuy.dao.find(sql.toString());
	this.setAttr("toConfirmOrderLst", toConfirmOrderLst);
	
	
	
	
	
	this.renderJsp("/weixin/member-product.jsp");
    }
    /**
    * 显示可退换货和已退换货的订单
    * @Title: reqrefundlst 
    * @Description: TODO(这里用一句话描述这个方法的作用) 
    * @param     设定文件 
    * @return void    返回类型 
    * @throws
     */
    public void reqrefundlst()
    {
	String openId = "";
	if (this.getSessionAttr("openId") != null) {
	    openId = this.getSessionAttr("openId").toString();
	}
	
	//所有的订单，不包括删除的，buystate=-1 
	String whereSql ="  openid='"+openId+"'";
	String orderSql=" order by createtime desc";
	String selectSql="select * from member_buy where postconstate=1";
	StringBuilder sql = new StringBuilder(selectSql);
	if(!"".equals(openId)){
	    sql.append(" and ").append(whereSql);
	}
	sql.append(orderSql);
	
	List<MemberBuy> allMayBackLst= MemberBuy.dao.find(sql.toString());
	this.setAttr("allMayBackLst", allMayBackLst);
	
	sql = new StringBuilder(selectSql).append(" and buystate=-2");
	if(!"".equals(openId)){
	    sql.append(" and ").append(whereSql);
	}
	sql.append(orderSql);
	
	List<MemberBuy> allOrderLst= MemberBuy.dao.find(sql.toString());
	this.setAttr("allOrderLst", allOrderLst);
	
	
	this.renderJsp("/weixin/back-goods-list.jsp");
    }
    
    public void reqrefund()
    {
	this.renderJsp("/weixin/back-goods.jsp");
    }

    /**
     * 我的二维码 验证跳转或者从个人中心过来
     * 
     * @throws UnsupportedEncodingException
     */
    public void membercard() throws UnsupportedEncodingException {
	String openId = "";
	if (this.getPara("code") != null) {
	    openId = oauth2Url(this.getPara("code"));
	}
	if (openId == null || "".equals(openId)) {
	    if (this.getSessionAttr("openId") != null) {
		openId = this.getSessionAttr("openId").toString();
	    }
	}

	if (!"".equals(openId)) {
	    WeixinSubscribe subscribe = new WeixinSubscribe();
	    subscribe.setFromusername(openId);
	    String ticket = Db.queryStr("select myticket from weixin_subscribe where fromusername=?", openId);
	    if (ticket.isEmpty()) {
		WeiXinUtil weiXinUtil = new WeiXinUtil();
		String accessToken = weiXinUtil.getAccessToken();
		ticket = weiXinUtil.getTicketForCreateOwerCard(accessToken, openId);
		Db.update("update weixin_subscribe set myticket=? where fromusername=?", ticket, openId);
	    }
	    setAttr("ticket", ticket);
	    System.out.println(ticket);
	}
	this.renderJsp("/weixin/member-card.jsp");
    }

    public void memberaddr() {
	String openId = "";
	if (this.getSessionAttr("openId") != null) {
	    openId = this.getSessionAttr("openId").toString();
	}
	String sql = "select * from member_address where openid ='" + openId + "'   order by createtime desc";
	List<MemberAddress> memberAddressLst = MemberAddress.dao.find(sql);
	setAttr("addresses", memberAddressLst);
	renderJsp("/weixin/member-address.jsp");
    }

    public void addrdefault() {
	JSONObject json = new JSONObject();
	boolean flag = false;
	String msg = "";
	try {
	    // String openId= this.getSessionAttr("openId").toString();
	    String openId = "";
	    String addressId = this.getPara("addressId").toString();
	    String sql = "update member_address set isdefault=1 where openid ='" + openId + "' and addressid="
		    + addressId;
	    Db.update(sql);
	    sql = "update member_address set isdefault=0 where openid ='" + openId + "' and addressid!=" + addressId;
	    Db.update(sql);
	    msg = "成功设置为默认收货地址！";
	    flag = true;
	    json.put("msg", msg);
	} catch (Exception e) {
	    json.put("msg", e.getMessage());
	}
	json.put("flag", flag);
	renderJson(json);
    }

    public void memberaddaddr() {
	if (this.getPara("pagesrc") != null) {
	    this.setAttr("pagesrc", "buy");
	} else {
	    this.setAttr("pagesrc", "address");
	}
	renderJsp("/weixin/member-add-address.jsp");
    }

    public void membereditaddr() {

	String addressId = this.getPara("addressId").toString();
	MemberAddress memberAddress = MemberAddress.dao.findById(addressId);
	this.setAttr("memberAddress", memberAddress);
	renderJsp("/weixin/member-add-address.jsp");

    }

    public void memberaddsave() {
	String openId = "";
	if (this.getSessionAttr("openId") != null) {
	    openId = this.getSessionAttr("openId").toString();
	}
	MemberAddress memberAddress = getModel(MemberAddress.class);
	memberAddress.setState(CommonConstant.VALIDATESATE);
	memberAddress.setOpenid(openId);
	if (memberAddress.getAddressid() == null) {
	    memberAddress.save();
	    this.setAttr("msg", "成功添加收货地址！");
	} else {
	    memberAddress.update();
	    this.setAttr("msg", "成功修改收货地址！");
	}
	this.setAttr("pagesrc", this.getPara("pagesrc"));

	renderJsp("/weixin/member-add-address.jsp");
    }

    public void deleteaddr() {
	String addressId = this.getPara("addressId").toString();
	MemberAddress memberAddress = new MemberAddress();
	memberAddress.setState(CommonConstant.INVALIDATESATE);
	memberAddress.setAddressid(Long.valueOf(addressId));
	memberAddress.dao.update();
	renderJson("成功删除收货地址！");
    }

    public void choosegoods() {
	String openId = "";
	if (this.getSessionAttr("openId") != null) {
	    openId = this.getSessionAttr("openId").toString();
	}
	this.setAttr("openId", openId);
	String memeberType = WeixinMemberInfoUtil.getWeixinSubscribe(openId).getMembertypecode();
	SettingMemberType sysMemeberType = WeixinMemberInfoUtil.getMemberType(memeberType);
	this.setAttr("sysMemeberType", sysMemeberType);
	renderJsp("/weixin/choose-goods.jsp");
    }

    public void member() {
	render("/weixin/member.html");
    }

    public void memberupinfo() {
	String reqopenId = this.getPara("reqopenId");
	String sql = "select * from member_shop_req where openid='" + reqopenId + "' order by createtime desc";

	MemberShopReq memberShopReq = MemberShopReq.dao.findFirst(sql);

	this.setAttr("memberShopReq", memberShopReq);
	sql = "select * from weixin_userinfo where openid='" + reqopenId + "' order by createtime desc";
	WeixinUserinfo userinfo = WeixinUserinfo.dao.findFirst(sql);
	this.setAttr("userinfo", userinfo);
	this.setAttr("reqopenId", reqopenId);
	renderJsp("/weixin/member-upconfirm.jsp");
    }

    /**
     * 微信接口配置信息URLhttp://miaowxtest.ngrok.cc/studentdrip/weixin/token
     */
    public void token() {
	try {
	    System.out.println("signature::::" + this.getRequest().getParameter("signature"));
	    System.out.println("echostr:::::" + this.getRequest().getParameter("echostr"));
	    System.out.println("timestamp:::::" + this.getRequest().getParameter("timestamp"));
	    System.out.println("nonce::::::" + this.getRequest().getParameter("nonce"));
	} catch (Exception e) {
	    e.printStackTrace();
	}
	this.renderText(this.getRequest().getParameter("echostr"));
    }

    /**
     * 页面授权跳转得到OPENID
     * 
     * @param code
     * @return
     */
    private String oauth2Url(String code) {
	String CodeUrl;
	String weixinauth_uri = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
	CodeUrl = weixinauth_uri.replace("APPID", PropKit.get("appid")).replace("SECRET", PropKit.get("secret"))
		.replace("CODE", code);
	String ret = HttpRequest.sendGet(CodeUrl);
	System.out.println(ret);
	Map map = WeiXinUtil.getMapFromJson(ret);
	if (map.get("openid") != null) {
	    String openId = map.get("openid").toString();
	    System.out.println("openid::::" + openId);
	    setSessionAttr("openId", openId);
	    return openId;
	}
	return null;
    }

}
